#import <objc/runtime.h>
#import "UIImageView+Extension.h"

#define	UIImageViewFromAlbum		@"imageFromAlbums"

@implementation UIImageView (Extension)

/*===================================================================
 说明:
	添加倒影
 ==================================================================*/
- (void)makeReflection
{
	[self makeReflectionForParcent:1];
}

- (void)makeReflectionForParcent:(CGFloat)parcent
{
	CALayer *layer = [CALayer layer];
	
	//渐变遮罩
	CAGradientLayer *gradient = [[CAGradientLayer alloc] init];
	
	gradient.colors = @[(id)rgba(0,0,0,.4).CGColor, (id)rgba(0,0,0,0).CGColor];
	gradient.startPoint = CGPointMake(.5, 1);
	gradient.endPoint = CGPointMake(.5, 1-parcent);
	
	//倒影为X轴镜像
	layer.contents = (id)self.image.CGImage;
	layer.mask = gradient;
	layer.transform = CATransform3DMakeRotation(M_PI, 1, 0, 0);
	
	CGRect frame = self.bounds;
	layer.frame = CGRectOffset(self.bounds, 0, CGRectGetMaxY(frame));
	layer.mask.frame = layer.bounds;
	
	[self.layer addSublayer:layer];
}

/*===================================================================
 说明:
    在相册中获取指定大小的相片
 ==================================================================*/
#pragma mark - 获取相册
- (void)imageFromAlbumsWithSize:(CGSize)size handler:(AlbumsResult)handler
{
	NSString    *albums = L(@"IDS_ALBUMS");
    NSString    *camera = L(@"IDS_CAMERA");
    NSString    *cancel = L(@"IDS_CANCEL");
	
	objc_setAssociatedObject(self, UIImageViewFromAlbum, @[handler, [NSValue valueWithCGSize:size]], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	
	if (IOS8)	//IOS9要使用UIAlerControler，不然UIActionSheet会与键盘冲突
	{
		UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
		
		__weak id this = self;
		__weak UIViewController *viewController = self.viewController;
		
		//拍照
		if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
		{
			[sheet addAction:[UIAlertAction actionWithTitle:camera style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
				
				UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
				
				imagePicker.delegate = this;
				imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
				imagePicker.allowsEditing = YES;
				
				[viewController showViewController:imagePicker];
			}]];
		}
		
		//相册选择
		[sheet addAction:[UIAlertAction actionWithTitle:albums style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
			
			UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
			
			imagePicker.delegate = this;
			imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
			imagePicker.allowsEditing = YES;
			
			[viewController showViewController:imagePicker];
		}]];
		
		[sheet addAction:[UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleCancel handler:nil]];
        
		[viewController showViewController:sheet];
	}
	else//非iOS8
	{
		UIActionSheet *sheet = [UIActionSheet alloc];
		
		if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
			sheet = [sheet initWithTitle:nil delegate:self cancelButtonTitle:cancel destructiveButtonTitle:nil otherButtonTitles:camera, albums, nil];
		else
			sheet = [sheet initWithTitle:nil delegate:self cancelButtonTitle:cancel destructiveButtonTitle:nil otherButtonTitles:albums, nil];
		
		[sheet showInView:self];
	}
}

/*===================================================================
 说明：
    选择类型
 ==================================================================*/
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    NSUInteger sourceType = -1;
    
    // 判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        if (buttonIndex == 0) sourceType = UIImagePickerControllerSourceTypeCamera;				//拍照
        if (buttonIndex == 1) sourceType = UIImagePickerControllerSourceTypePhotoLibrary;		//相册
    }
    else
    {
        if (buttonIndex == 0) sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;   //相册
    }
    
    if (sourceType != -1)
    {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        
        imagePicker.delegate = self;
        imagePicker.sourceType = sourceType;
        imagePicker.allowsEditing = YES;
        
        [self.viewController showViewController:imagePicker];
    }
}

/*===================================================================
 说明：
    选择器风格
 ==================================================================*/
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
	//navigationController.view.backgroundColor = app.color;
	navigationController.navigationBar.translucent = NO;
	
	navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
	[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

/*===================================================================
 说明：
    取消选择
 ==================================================================*/
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	objc_removeAssociatedObjects(self);
	
    [picker dismissViewControllerAnimated:YES completion:nil];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

/*===================================================================
 说明：
    选择用户头像
 ==================================================================*/
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *newImage = [info objectForKey:UIImagePickerControllerEditedImage];
	
	//目标图像大小
    NSArray *a = objc_getAssociatedObject(self, UIImageViewFromAlbum);
    CGSize size = ((NSValue *)a.lastObject).CGSizeValue;
	
	UIGraphicsBeginImageContext(size);
	
	[newImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
	
	UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
    
    AlbumsResult handler = a.firstObject;
    if (handler) handler(self, image);
	
	[self imagePickerControllerDidCancel:picker];
}

@end
